package com.deer.wms.ASN.manage.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.deer.wms.ASN.manage.constant.AsnManageConstant;
import com.deer.wms.ASN.manage.model.file.FileData;
import com.deer.wms.ASN.manage.model.in.AcceptRecord;
import com.deer.wms.ASN.manage.model.in.AcceptRecordCriteria;
import com.deer.wms.ASN.manage.model.qc.*;
import com.deer.wms.ASN.manage.service.AcceptRecordService;
import com.deer.wms.ASN.manage.service.AsnMasterService;
import com.deer.wms.ASN.manage.service.QcRecordService;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.system.manage.constant.SystemManageConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
*
 * @author guo
 * @since 2020/01/15
 */
@Api(description = "质检记录api接口")
@RestController
@RequestMapping("/qc/records")
public class QcRecordController {
    @Autowired
    private QcRecordService qcRecordService;
    @Autowired
    private AcceptRecordService acceptRecordService;
    @Value("${prj.name}")
    private String name;

    /**
     * 质检记录导出方法
     * @param  response     查询条件
     * @return   返回结果
     * @since  1.0
     * @deprecated
     */
    @GetMapping("/exportExcel")
    public String exportExcel(HttpServletResponse response, String keyWords, String asnMasterCode, String acceptRecordCode, String batchName,  String startTime, String endTime) throws Exception{
        qcRecordService.exportExcel(response,keyWords,asnMasterCode,acceptRecordCode,batchName,startTime,endTime);
        return "";
    }
    @PostMapping("/insert")
    public Result add(@RequestBody QcRecord qcRecord) {
        qcRecordService.save(qcRecord);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        qcRecordService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody QcRecord qcRecord) {
        qcRecordService.updateById(qcRecord);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        QcRecord qcRecord = qcRecordService.getById(id);
        return ResultGenerator.genSuccessResult(qcRecord);
    }

    @GetMapping("/list")
    public Result list(QcRecordCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<QcRecordDto> list = qcRecordService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/return/list")
    public Result returnList(QcRecordCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<QcRecordDto> list = qcRecordService.findReturnList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }
    @ApiOperation(value = "质检撤销")
    @PostMapping("/cancelqc")
    @Transactional
    public Result cancelQc(@RequestBody QcRecord qcRecord, @ApiIgnore @User CurrentUser currentUser) {
          qcRecordService.cancelQc(qcRecord.getQcRecordCode(),currentUser);
          return ResultGenerator.genSuccessResult();
    }
    @ApiOperation(value = "确认不合格")
    @PostMapping("/cancelNQ")
    @Transactional
    public Result cancelNQ(@RequestBody QcRecord qcRecord, @ApiIgnore @User CurrentUser currentUser) {
        qcRecordService.cancelNQ(qcRecord.getQcRecordCode(),currentUser);
        return ResultGenerator.genSuccessResult();
    }
    @ApiOperation(value = "批量质检提交")
    @PostMapping("/submit")
    @Transactional
    public Result submit(@RequestBody QcResultCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if (criteria.getQcRecordList() != null) {
            List<QcRecord> qcRecordList = criteria.getQcRecordList();
            AcceptRecord acceptRecords=acceptRecordService.getOneByField("accept_record_code",qcRecordList.get(0).getAcceptRecordCode());
            for (QcRecord qcRecord : qcRecordList) {
                QcResultCriteria qcResultCriteria = new QcResultCriteria();
                qcResultCriteria.setBillCode(qcRecord.getAcceptRecordCode());
                //此处只有全部合格跟全部不合格
                if(qcRecord.getQcResult().equals(0)){
                    //合格数量
                    qcResultCriteria.setQualifiedQuantity(acceptRecords.getQuantity());
                    //不合格
                    qcResultCriteria.setFiedQuantity(0.0);
                }else{
                    //合格数量
                    qcResultCriteria.setQualifiedQuantity(0.0);
                    //不合格
                    qcResultCriteria.setFiedQuantity(acceptRecords.getQuantity());
                }
                //检验时间qcTime
                qcResultCriteria.setQcTime(DateUtil.now());
                //备注
                qcResultCriteria.setMemo(qcRecord.getMemo());
                QcRecord newQcRecord = qcRecordService.qcResult(qcResultCriteria, currentUser);
                //回传erp
                //
                if ("jy".equals(name)) {
                    AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", qcRecord.getAcceptRecordCode());
                    acceptRecordService.billToErpNew(acceptRecord.getAsnBillNo(), newQcRecord);
                }
            }
        } else {


            //全部合格
//            AcceptRecordCriteria acceptRecordCriteria = new AcceptRecordCriteria();
//            acceptRecordCriteria.setAsnBillNo(criteria.getBillCode());
//            List<AcceptRecord> list = acceptRecordService.findList(acceptRecordCriteria);
//            for (AcceptRecord acceptRecord : list) {
//                if (acceptRecord.getQcState() != 2) {
//                    QcResultCriteria qcResultCriteria = new QcResultCriteria();
//                    qcResultCriteria.setBillCode(acceptRecord.getAcceptRecordCode());
//                    qcResultCriteria.setQcResult(1);
//                    //合格数量
//                    qcResultCriteria.setQualifiedQuantity(acceptRecord.getQuantity());
//                    //不合格数量fiedQuantity
//                    qcResultCriteria.setFiedQuantity(0.0);
//                    //让步数量concessionQuantity
//                    qcResultCriteria.setConcessionQuantity(0.0);
//                    //检验时间qcTime
//                    qcResultCriteria.setQcTime(DateUtils.getNowDateTimeString());
//                    qcRecordService.qcResult(qcResultCriteria, currentUser);
                    //回传erp
//                AcceptRecord acceptRecord = acceptRecordService.getOneByField("accept_record_code", criteria.getBillCode());
//                    String billId = acceptRecordService.billToErpNew(acceptRecord.getAsnBillNo(), qcResultCriteria.getBillCode());
                    //erp审核回传
//                    acceptRecordService.checkBillToErp(billId);
                }
//            }
//        }
         return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "退料确认")
    @PostMapping("/return/confirm")
    public Result returnConfirm(@RequestBody QcResultCriteria criteria) {
        Set<Integer> qcRecordIds = criteria.getQcRecordList().stream().map(qcRecord -> qcRecord.getQcRecordId()).collect(Collectors.toSet());
        List<QcRecord> qcRecords = qcRecordService.listByIds(qcRecordIds);

        qcRecordService.returnConfirm(qcRecords);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "让步")
    @PostMapping("/concession")
    public Result concession(@RequestBody QcResultCriteria criteria) {
        List<QcRecord> qcRecordList = criteria.getQcRecordList();
        Map<Integer, Double> map = new HashMap<>();
        for (QcRecord record : qcRecordList) {
            //先要判断是否已退料
            if (ObjectUtil.equal(record.getReturnState(), 1)) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "已退料确认，不允许再次让步!");
            }
            map.put(record.getQcRecordId(), record.getConcessionQuantity());
        }

        qcRecordService.concession(map);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "归档质检记录 传billNo", notes = "归档质检记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/file")
    public Result file(@RequestBody FileData fileData, @ApiIgnore @User CurrentUser currentUser) {
        if(currentUser == null){
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        for(int i=0;i<fileData.getDetailNos().size();i++){
            String detailNo = fileData.getDetailNos().get(i);
            qcRecordService.createFile(detailNo,currentUser);
        }

        return ResultGenerator.genSuccessResult();
    }

}
